package com.ruoyi.myoa.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.activiti.domain.HistoricActivity;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.rabbitmq.RabbitMqUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.RabbitmqConfig;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.myoa.domain.BizLeave;
import com.ruoyi.myoa.service.IBizLeaveService;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.report.utils.JasperUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 请假Controller
 *
 * @author
 */
@RestController
@RequestMapping("/leave/leave")
@AllArgsConstructor
public class BizLeaveController extends BaseController
{
    private IBizLeaveService bizLeaveService;
    private IProcessService processService;
    private ISysUserService userMapper;
    private ISysDictTypeService dictTypeService;
    private RabbitMqUtils rabbitMqUtils;
    private HistoryService historyService;

    /**
     * 查询请假列表
     */
//    @PreAuthorize("@ss.hasPermi('leave:leave:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizLeave bizLeave)
    {
        startPage();
        List<BizLeave> list = bizLeaveService.selectBizLeaveList(bizLeave);
        return getDataTable(list);
    }

    /**
     * 导出请假列表
     */
//    @PreAuthorize("@ss.hasPermi('leave:leave:export')")
    @Log(title = "请假", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizLeave bizLeave)
    {
        List<BizLeave> list = bizLeaveService.selectBizLeaveList(bizLeave);
        ExcelUtil<BizLeave> util = new ExcelUtil<BizLeave>(BizLeave.class);
        return util.exportExcel(list, "leave");
    }

    /**
     * 获取请假详细信息
     */
//    @PreAuthorize("@ss.hasPermi('leave:leave:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bizLeaveService.selectBizLeaveById(id));
    }

    /**
     * 获取请假详细信息bpmid
     */
    @GetMapping(value = "/bpmid/{bpmid}")
    public AjaxResult getInfobyBpmid(@PathVariable("bpmid") String bpmid)
    {
        return AjaxResult.success(bizLeaveService.selectBizLeaveByBpmid(bpmid));
    }

    /**
     * 新增请假
     */
//    @PreAuthorize("@ss.hasPermi('leave:leave:add')")
    @Log(title = "请假", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizLeave bizLeave)
    {
        return toAjax(bizLeaveService.insertBizLeave(bizLeave));
    }


    @Log(title = "请假打印", businessType = BusinessType.EXPORT)
    @PostMapping("/print")
    public void print(@RequestBody BizLeave bizLeave, HttpServletResponse response)
    {
        String tempath = "template/qjsq/test.jrxml";
        BizLeave bizLeaveinfo = bizLeaveService.selectBizLeaveByBpmid(bizLeave.getBpmid());
        List<SysDictData> dictdata = dictTypeService.selectDictDataByType("sys_leave_type");

        Map<String,Object> printinfo = new HashMap<String,Object>();
        dictdata = dictdata.stream().filter(SysDictData -> SysDictData.getDictValue().equals(bizLeaveinfo.getType())).collect(Collectors.toList());

        printinfo.put("name",userMapper.selectUserByUserName(bizLeaveinfo.getCreateBy()).getNickName());
        printinfo.put("leavestarttime",bizLeaveinfo.getLeaveStartTime());
        printinfo.put("leaveendtime",bizLeaveinfo.getLeaveEndTime());
        printinfo.put("leavetype",dictdata.get(0).getDictLabel());
        printinfo.put("yuanyin",bizLeaveinfo.getReason());
        printinfo.put("beizhu",bizLeaveinfo.getRemark());
        printinfo.put("printtime",new Date());

        HistoricActivity historicActivity = new HistoricActivity();
        historicActivity.setProcessInstanceId(bizLeave.getInstanceId());
        List<HistoricActivity> splist = processService.selectHistoryList(historicActivity);

        String yinzhangBase64 = JasperUtils.imageToBase64("template/png/PASS.png");
        printinfo.put("yinzhang",yinzhangBase64);
        JasperUtils.preViewPdfAndList(response,tempath,printinfo,splist);
    }
    /**
     * 修改请假
     */
//    @PreAuthorize("@ss.hasPermi('leave:leave:edit')")
    @Log(title = "请假", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizLeave bizLeave)
    {
        return toAjax(bizLeaveService.updateBizLeave(bizLeave));
    }

    /**
     * 删除请假
     */
//    @PreAuthorize("@ss.hasPermi('leave:leave:remove')")
    @Log(title = "请假", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizLeaveService.deleteBizLeaveByIds(ids));
    }

    /**
     * 提交申请
     */
    @Log(title = "请假业务", businessType = BusinessType.UPDATE)
    @PostMapping( "/submitApply/{id}")
    @ResponseBody
    public AjaxResult submitApply(@PathVariable Long id) {
        try {
            Map<String,Object> variables = new HashMap<String,Object>();
            String title = "【"+userMapper.selectUserByUserName(SecurityUtils.getUsername()).getNickName()+"】的请假申请";
            variables.put("title", title);
            BizLeave bizLeave = bizLeaveService.selectBizLeaveById(id);
            HashMap<String,Object> actre = processService.submitApply(bizLeave, "test", variables);
            bizLeaveService.updateBizLeave(bizLeave);


            //向前端推送消息
            String tenantId = DynamicDataSourceContextHolder.getDataSourceType();
            HashSet<String> nowspr = new HashSet<>();
            nowspr =  actre.get("nowspr")==null ? null : (HashSet<String>)actre.get("nowspr");
            rabbitMqUtils.sendRabbitBpmMsg(RabbitmqConfig.EXCHANGE_TOPIC_INFORM, nowspr,"提示","你有一条新的请假流程待办需要审批","/wdlc/dbsq",tenantId);


        } catch (Exception e) {
            e.printStackTrace();
            return error("提交申请出错：" + e.getMessage());
        }
        return success();
    }


    /**
     * 办理任务
     */
    @PostMapping( "/complete")
    @ResponseBody
    public AjaxResult complete(String taskId, String instanceId,String bpmid, String variables) {
        HashMap<String,Object> actre =  processService.complete(taskId, instanceId,bpmid, variables);
        System.out.println("actre = " + actre.toString());
        System.out.println("bpmid = " + bpmid);
        //更改业务表审批状态
        BizLeave bizLeave = new BizLeave();
        bizLeave.setBpmid(bpmid);
        String tenantId = DynamicDataSourceContextHolder.getDataSourceType();
        if((Boolean)actre.get("isend") == true){
          if((Boolean) actre.get("pass")==true ){
            bizLeave.setSpzt(1);
              //向前端推送消息 审批完成
              HashSet<String> nowspr = new HashSet<>();
              nowspr.add((String) actre.get("faqiren"));
              rabbitMqUtils.sendRabbitBpmMsg(RabbitmqConfig.EXCHANGE_TOPIC_INFORM, nowspr,"提示","你有一条请假流程审批通过","/wdlc/dbsq",tenantId);

          }else{
            bizLeave.setSpzt(4);
              //向前端推送消息 审批撤销
              HashSet<String> nowspr = new HashSet<>();
              nowspr.add((String) actre.get("faqiren"));
              rabbitMqUtils.sendRabbitBpmMsg(RabbitmqConfig.EXCHANGE_TOPIC_INFORM, nowspr,"提示","你撤销了一条请假申请","/wdlc/dbsq",tenantId);

          }
        }else{
            if((Boolean) actre.get("pass")==false){
                bizLeave.setSpzt(3);

                //向前端推送消息 审批中
                HashSet<String> nowspr = new HashSet<>();
                nowspr =  actre.get("nowspr")==null ? null : (HashSet<String>)actre.get("nowspr");
                rabbitMqUtils.sendRabbitBpmMsg(RabbitmqConfig.EXCHANGE_TOPIC_INFORM, nowspr,"提示","你有一条新的请假流程被退回","/wdlc/dbsq",tenantId);

            }else {
                bizLeave.setSpzt(2);

                //向前端推送消息 审批中
                HashSet<String> nowspr = new HashSet<>();
                nowspr =  actre.get("nowspr")==null ? null : (HashSet<String>)actre.get("nowspr");
                rabbitMqUtils.sendRabbitBpmMsg(RabbitmqConfig.EXCHANGE_TOPIC_INFORM, nowspr,"提示","你有一条新的请假流程待办需要审批","/wdlc/dbsq",tenantId);

            }
        }

        bizLeaveService.upSpztByBpmid(bizLeave);
        return success();
    }

}
